const zbPanel = function() {
    this.instance = 'zbPanel';
    this.imgUpArrow = '/summer/icons/up-arrow.png';
    this.imgDownArrow = '/summer/icons/down-arrow.png';
    this.onHide = null; //隐藏body后回调
    this.onShow = null; //显示body后回调
    this.onRender = null;//调用this.show方法后执行
    this.content = '';
    this.tpl =
        '<div class="zb-panel-list">\
            <div class="box" id="{panel_id}">\
                <div class="title" id="pt_{title_id}">\
                    <div class="title-idx">{idx}</div>\
                    <div class="title-name">{name}</div>\
                    <div class="title-icon zb-icon-down-arrow" onclick="{_instance}.togglePanel(\'{title_id}\')">&nbsp;</div>\
                </div>\
                <div class="body hide" id="pb_{body_id}"> {content} </div>\
                <div class="footer hide" id="pf_{footer_id}"> {content} </div>\
            </div>\
        </div>';

    this.initCss = function() {
        let flag = document.getElementsByClassName('zb-panel-list');
        if (!flag || flag.length === 0) {
            let style = document.createElement('style');
            style.innerText =
                '.hide{display:none}'+
                '.show{display:block}'+
                '.zb-icon-up-arrow {background-image: url(\''+this.imgUpArrow+'\'); background-size: 100% 100%; background-repeat: no-repeat;}' +
                '.zb-icon-down-arrow {background-image: url(\''+this.imgDownArrow+'\'); background-size: 100% 100%; background-repeat: no-repeat;}' +
                '.zb-panel-list {padding: 2px; display: flex; flex-direction: column; justify-content: flex-start; align-items: stretch;}' +
                '.zb-panel-list .box {border-bottom: 1px solid #c8c8c8;}' +
                '.zb-panel-list .title {display: flex;flex-direction: row;justify-content: space-between; align-items: center; padding: 5px;}' +
                '.zb-panel-list .title-idx {max-width: 50px;overflow-x: scroll; padding: 3px 0;}' +
                '.zb-panel-list .title-idx::-webkit-scrollbar {display: none;}' +
                '.zb-panel-list .title-name {flex-grow: 1;overflow-x: scroll; padding: 3px 0; margin-left: 8px;}' +
                '.zb-panel-list .title-name::-webkit-scrollbar {display: none;}' +
                '.zb-panel-list .title-icon {width: 18px;}' +
                '.zb-panel-list .body {padding: 5px;margin-top: 3px;}' +
                '.zb-panel-list .footer {padding: 5px; font-size:12px; text-align:right;}'
            ;

            let head = document.getElementsByTagName('head')[0];
            head.appendChild(style);
        }
    }

    //初始化
    this.init = function(instance, data, config){

        this.instance = instance;

        if (config['imgUpArrow']) {
            this.imgUpArrow = config['imgUpArrow'];
        }
        if (config['imgDownArrow']) {
            this.imgDownArrow = config['imgDownArrow'];
        }

        this.initCss();

        //data中的box需要是数组, 表示有多个panel
        for (let i=0; i<data['box'].length; i++) {
            data['box'][i]['title']['_instance'] = this.instance;
            data['box'][i]['title']['title_id'] = data['box'][i]['panel_id'];
            data['box'][i]['body']['body_id'] = data['box'][i]['panel_id'];
            data['box'][i]['footer']['footer_id'] = data['box'][i]['panel_id'];
        }

        console.log(data);

        let node = this.htmlToNode(this.tpl);
        this.content = this.repeatNode(node, [data]);
    }


    this.show = function(id) {
        document.getElementById(id).innerHTML = this.content;
        if (typeof this.onRender === 'function') {
            this.onRender();
        }
    }

    //展开/折叠body/footer
    this.togglePanel = function (panel_id) {
        let box = document.getElementById(panel_id);
        let title_action = box.getElementsByClassName('title')[0].getElementsByClassName('title-icon')[0];

        let hide = 'zb-icon-up-arrow';
        let show = 'zb-icon-down-arrow';

        let display = '';
        if (title_action.classList.contains(hide)) { //当前是上箭头
            display = 'hide';
            title_action.classList.remove(hide);
            title_action.classList.add(show);
            if (typeof this.onHide === 'function') {
                this.onHide(panel_id);
            }
        } else {
            display = 'show';
            title_action.classList.remove(show);
            title_action.classList.add(hide);
            if (typeof this.onShow === 'function') {
                this.onShow(panel_id);
            }
        }

        let body = document.getElementById('pb_'+panel_id);
        body.classList.remove('hide');
        body.classList.remove('show');
        body.classList.add(display);

        let footer = document.getElementById('pf_'+panel_id);
        footer.classList.remove('hide');
        footer.classList.remove('show');
        footer.classList.add(display);

    }

    this.getTitleId = function(id) {
        return 'pt_'+id;
    }

    this.getBodyId = function(id) {
        return 'pb_'+id;
    }

    this.getFooterId = function(id) {
        return 'pt=f_'+id;
    }

    this.htmlToNode = function(html) {
        let div = document.createElement('div');
        div.innerHTML = html;
        return div.firstElementChild;
    }

    this.repeatString = function (tplDom, arr, func=null) {
        if (tplDom.length === 0) {
            this.error('字符串长度为空');
            return;
        }

        if (arr.length === 0) {
            this.error('数据为空');
            return tplDom;
        }

        let tpl = tplDom;
        let out = '';
        for (let i=0; i<arr.length; i++) {
            if (typeof func === 'function') {
                arr[i] = func(arr[i]);
            }
            let map = arr[i];
            let tmp = tpl;
            for (let j in map) {
                let re = new RegExp('{' + j + '}', 'g');
                tmp = tmp.replace(re, map[j]);
            }

            let re = new RegExp('{_idx}', 'g');
            tmp = tmp.replace(re, parseInt(i)+1);

            out += tmp;
        }

        return out;
    };

    /**
     * @param node HTML DOM节点, 注意不是string
     * @param arr json数组 注意是数组类型
     * @return string 返回HTML字符串, 注意不是DOM节点
     */
    this.repeatNode = function (node, arr) {
        let out = [];
        for (let i=0; i<arr.length; i++) {
            let tmp = node.outerHTML;
            tmp = tmp.replace(/\s/g, ' '); //去掉回车换行, 减少空白符

            let map = arr[i];

            //先渲染内层的数组
            for (let j in map) {
                if (map[j] instanceof Array) { //数组, 递归替换
                    let subNode = node.querySelector('.'+j);
                    let subHtml = this.repeatNode(subNode, map[j]); //递归
                    let subTpl = subNode.outerHTML.replace(/\s/g, ' ');
                    tmp = tmp.replace(subTpl, subHtml);

                }
            }

            //再渲染内层的对象
            for (let j in map) {
                console.log(map[j]);
                if (map[j] instanceof Object && !(map[j] instanceof Array)) { //对象, 递归替换
                    let subNode = node.querySelector('.'+j);
                    let subHtml = this.repeatNode(subNode, [map[j]]); //递归
                    let subTpl = subNode.outerHTML.replace(/\s/g, ' ')
                    tmp = tmp.replace(subTpl, subHtml);

                }
            }

            //最后渲染外层的键值对/字符串
            for (let j in map) {
                console.log(map[j]);
                if (typeof map[j] === 'string' || typeof map[j] === 'number') { //字符串/数字, 直接替换
                    let re = new RegExp('{' + j + '}', 'g');
                    tmp = tmp.replace(re, map[j]);

                }
            }

            out.push(tmp);
        }

        return out.join('');
    }

}


/**
 * 测试用例

 let panel = new zbPanel();
 let config = {
			imgUpArrow:'/static/img/up-arrow.png',
			imgDownArrow:'/static/img/down-arrow.png',
		};
 let data = {
			'box':[
			{
				'panel_id': '1111',
				'title':{
					'idx':1,
					'name':'测试-name1',
				},
				'body':{
					'content': '<p>Hello World!</p>'
				},
				'footer':{
					'content':'1111111'
				}

			},
			{
				'panel_id': '222',
				'title':{
					'idx':2,
					'name':'测试-name2',
				},
				'body':{
					'content': '<p>Hello World!</p>'
				},
				'footer':{
					'content': '222222'
				}

			}
			]
		}
    panel.init('panel',data,config);
    panel.onShow = function(id) {
			alert('显示-'+id);
		}
    panel.onHide = function(id) {
			alert('隐藏-'+id);
		}
    panel.onRender = function() {
			panel.togglePanel('1111'); //主动触发折叠事件
		}
    panel.show('aaa');

 */